package com.ruoyi.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.Evaluation;
import com.ruoyi.business.domain.HomeworkStuAnswer;
import com.ruoyi.business.domain.bo.HomeworkStuAnswerBo;
import com.ruoyi.business.mapper.EvaluationMapper;
import com.ruoyi.business.mapper.HomeworkStuAnswerMapper;
import com.ruoyi.business.question.QuestionHandle;
import com.ruoyi.business.question.QuestionHandleFactory;
import com.ruoyi.business.service.IHomeworkStuAnswerService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 最爱喝兽奶
 * @create 2022/9/29
 **/
@SuppressWarnings("ALL")
@Service
public class HomeworkStuAnswerServiceImpl extends ServiceImpl<HomeworkStuAnswerMapper, HomeworkStuAnswer> implements IHomeworkStuAnswerService {

    @Autowired
    private EvaluationMapper evaluationMapper;


    @Override
    public void submitHomework(List<HomeworkStuAnswerBo> list) {
        // 将学生的回答存入数据库中
        List<HomeworkStuAnswer> collect = list.stream().map(item -> {
            HomeworkStuAnswer homeworkStuAnswer = new HomeworkStuAnswer();
            BeanUtils.copyBeanProp(homeworkStuAnswer, item, true);
            // 进行计分
            QuestionHandle questionHandle = QuestionHandleFactory.createQuestionHandle(item.getType());
            assert questionHandle != null;
            Integer score = questionHandle.calcScore(item.getAnswer(), item.getQuestionId(), null);
            homeworkStuAnswer.setScore(score);
            return homeworkStuAnswer;
        }).collect(Collectors.toList());
        this.saveBatch(collect);
    }

    @Override
    public Integer querySubmitCount(String id) {
        Integer num = baseMapper.querySubmitCount(id);
        return num;
    }

    @Override
    public void submitSubjectiveEvaluation(List<HomeworkStuAnswerBo> bos) {
        // 当前互评了多少个人
        int currentLen = -1;
        long total = -1;
        int homeworkScore = 0;
        String[] tempScores = new String[0];
        String homeworkId = null;
        String responseUserId = null;
        String evaluationUserId = SecurityUtils.getUserId();
        String tempScore = null;
        for (HomeworkStuAnswerBo bo : bos) {
            if (currentLen == -1) {
                // 查询作业有多少人互评
                homeworkId = bo.getHomeworkId();
                responseUserId = bo.getUserId();
                total = evaluationMapper.selectCount(new QueryWrapper<Evaluation>().eq("homework_id", bo.getHomeworkId()).eq("response_user_id", bo.getUserId()));
            }
            // 查询当前已有多少人互评
            // 根据作业，用户，问题，查询出暂存的分数
            QueryWrapper<HomeworkStuAnswer> wrapper = new QueryWrapper<>();
            wrapper.eq("homework_id", bo.getHomeworkId());
            wrapper.eq("user_id", bo.getUserId());
            wrapper.eq("question_id", bo.getQuestionId());
            HomeworkStuAnswer homeworkStuAnswer = baseMapper.selectOne(wrapper);
            // 获取暂存的分数
            tempScore = homeworkStuAnswer.getTempScore();
            if (StringUtils.isNotBlank(tempScore)) {
                tempScores = tempScore.split(HomeworkStuAnswer.SEPARATOR);
                currentLen = tempScores.length;
            }else {
                currentLen = 0;
            }
            if (currentLen + 1 == total) {
                // 如果当前操作之后就是最终互评，就将最后的修改结果存入score中
                int sum = bo.getScore();
                for (int i = 0; i < tempScores.length; i++) {
                    sum += Integer.parseInt(tempScores[i]);
                }
                homeworkScore += sum / total;
                bo.setScore(sum / (int)total);
                bo.setTempScore(null);
            }else {
                bo.setTempScore(tempScore);
                if (currentLen + 2 != total) {
                    // 如果当前不是倒数第二个就新增逗号
                    if (null == bo.getTempScore()) {
                        bo.setTempScore(String.valueOf(bo.getScore()));
                    }else {
                        bo.setTempScore(bo.getTempScore() + HomeworkStuAnswer.SEPARATOR + String.valueOf(bo.getScore()));
                    }
                }
                bo.setScore(null);
            }
            baseMapper.updateScoreByQuestion(bo);
        }
        // 跟新互评的互评时间
        Evaluation evaluation = evaluationMapper.selectOne(new QueryWrapper<Evaluation>().eq("homework_id", homeworkId).eq("response_user_id", responseUserId).eq("evaluation_user_id", evaluationUserId));
        if (currentLen + 1 == total) {
            // 将互评对象查询出来
            // 创建一个互评对象
            // 查询出所有人的
            evaluation.setScore(homeworkScore);
        }
        evaluation.setIsEvaluation(1);
        evaluation.setEvaluationDate(new Date());
        evaluationMapper.updateById(evaluation);
    }

    /**
     * 判断是否有主观题
     * @param list
     * @return
     */
    private boolean hasSubjectQuestion(List<HomeworkStuAnswerBo> list) {
        for (HomeworkStuAnswerBo homeworkStuAnswerBo : list) {
            if ("3".equals(homeworkStuAnswerBo.getType()) || "4".equals(homeworkStuAnswerBo.getType())) {
                // 如果存在主观题就返回true，否则就返回false
                return true;
            }
        }
        return false;
    }
}
